﻿#if NET45
using System;
using System.Configuration;

namespace Longbow.Configuration
{
    /// <summary>
    /// 配置文件保存扩展类
    /// </summary>
    public static class LgbConfigurationManager
    {
        /// <summary>
        /// 更新指定AppSettings小节的KeyValue对，并不保存配置文件
        /// </summary>
        /// <param name="appSection"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void UpdateAppSettings(AppSettingsSection appSection, string key, string value)
        {
            if (appSection == null) throw new ArgumentNullException("appSection");
            if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key");

            if (appSection.Settings[key] == null)
                appSection.Settings.Add(key, value);
            else
                appSection.Settings[key].Value = value;
        }

        /// <summary>
        /// 保存AppSettings到配置文件中
        /// </summary>
        /// <param name="config"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SaveAppSettings(System.Configuration.Configuration config, string key, string value)
        {
            if (config == null) throw new ArgumentNullException("config");
            if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key");
            var section = config.AppSettings;
            if (section == null)
            {
                section = new AppSettingsSection();
                config.Sections.Add(section.SectionInformation.Name, section);
            }
            UpdateAppSettings(section, key, value);
            config.Save(ConfigurationSaveMode.Minimal);
        }
    }
}
#endif
